package com.example.wacoffee_manage.Service.Impl;

import com.example.wacoffee_manage.Mapper.OrderMapper;
import com.example.wacoffee_manage.Service.orderService;
import com.example.wacoffee_manage.pojo.Good;
import com.example.wacoffee_manage.pojo.Order;
import com.example.wacoffee_manage.pojo.TodayRevenue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class orderServiceImpl implements orderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void addOrder(Order order) {
        orderMapper.addOrder(order);
        orderMapper.updateStock(order.getItems());
        orderMapper.addOrderGood(order);
    }

    @Override
    public TodayRevenue getTodayOrder() {
        Double todayRevenue = orderMapper.getTodayRevenue();
        if (todayRevenue == null) {
            todayRevenue = 0.0; // 如果为空，默认设置为 0
        }
        Integer totalOrders= orderMapper.getTotalOrders();
        if (totalOrders == null) {
            totalOrders = 0; // 如果为空，默认设置为 0
        }
        Integer completedOrders = orderMapper.getCompletedOrders();
        if (completedOrders == null) {
            completedOrders = 0; // 如果为空，默认设置为 0
        }
        return new TodayRevenue(todayRevenue,totalOrders,completedOrders);
    }

    @Override
    public List<Order> getUnfinishedOrder() {
        return orderMapper.getUnfinishedOrder();
    }

    @Override
    public void updateOrder(Integer id) {
        orderMapper.updateOrder(id);
    }

    @Override
    public void updateOrderGood(int id) {
        List<Good> goods = orderMapper.getGoodsByOrderId(id);
        orderMapper.updateGoodStock(goods);
        orderMapper.updateOrderStatus2(id);
        Order order = orderMapper.getById(id);
        Integer userId = null;
        if (order != null) {
            userId = order.getUserId();
            double expend = order.getExpend();
            if (orderMapper.getById(id).getStatus() == 2 && userId != null) {
                orderMapper.addBalance(userId,expend);
            }
        }
    }

    @Override
    public Order getById(int orderId) {
        return orderMapper.getById(orderId);
    }
}
